package com.project.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.project.model.MemberModel;
import com.project.model.WxUserInfoModel;
import com.project.service.MemberService;
import com.project.service.WxUserInfoService;
import com.project.utils.AccessToken;
import com.project.utils.AppInfo;
import com.project.utils.OAuthInfo;
import com.project.utils.Sign;
import com.project.utils.WeixinUtil;

@Controller
@RequestMapping(value = "/wx")
public class WeixinOAuthController {
	private static Logger logger = LoggerFactory.getLogger(WeixinOAuthController.class);
	
	@Autowired
	private WxUserInfoService wxUserInfoService;
	
	@Autowired
	private MemberService memberService;
	
	private final String moduleName = "oauth";
	
	@RequestMapping(moduleName)
	public ModelAndView index(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		if (null != request.getSession().getAttribute("userId")) {
			String page = "/index";
			if (null != request.getParameter("page") && !"".equals(request.getParameter("page"))) {
				page = request.getParameter("page");
			}
			mav.setViewName(page);
		} else {
			int wx_id = 0;
			String nickname = "";
			String headimgurl = "";
			String code = request.getParameter("code");
			String page = "/register.jsp";
			if(null != code && !"".equals(code)){
	            logger.info("==============[OAuthServlet]获取网页授权code不为空，code="+code);
	            //根据code换取openId
				AccessToken accessToken = WeixinUtil.getAccessToken(AppInfo.appId, AppInfo.appSecret);
	            OAuthInfo oa = WeixinUtil.getOAuthOpenId(AppInfo.appId, AppInfo.appSecret, code);
	            // mav.addObject("errcode", info.getErrcode());
	            /*if (info.getErrcode().equals("40001")) {
	            	
	            }*/
	            if (null != oa) {
	            	WxUserInfoModel wxUserInfoModel = wxUserInfoService.getWxUserInfoModelByOpenid(oa.getOpenId());
	                if (null != wxUserInfoModel && wxUserInfoModel.getId() > 0) {
	                	// 用户已经认证过
	                	// int id = wxUserInfoService.update(wxUserInfoModel);
	                	wx_id = wxUserInfoModel.getId();
	                	nickname = wxUserInfoModel.getNickname();
	                	headimgurl = wxUserInfoModel.getHeadimgurl();
	                	List<MemberModel> imList = memberService.getMemberModelByWxId(wx_id);
	                	if (imList.size() > 0) {
	                		// 用户已经注册过
	                		HttpSession session = request.getSession();
	        				session.setAttribute("userId", imList.get(0).getId());
	        				memberService.updateLoginTime(imList.get(0).getId());
	        				page = "/index";
	        				if (null != request.getParameter("page") && !"".equals(request.getParameter("page"))) {
	        					page = request.getParameter("page");
	        				}
	                	} else {
	                		page = "/register.jsp";
	                	}
	                } else {
	                	// 用户第一次认证
	                	WxUserInfoModel info = WeixinUtil.getUserInfo(accessToken.getToken(), oa.getOpenId());
	                	int rel = wxUserInfoService.insert(info);
	                	if (rel > 0) {
	                		wx_id = info.getId();
	                		nickname = info.getNickname();
	                    	headimgurl = info.getHeadimgurl();
	                	}
	                	page = "/register.jsp";
	                }
	            } else {
	            	page = "/again_login.jsp";
					if (null != request.getParameter("page") && !"".equals(request.getParameter("page"))) {
						page = page + "?page=" + request.getParameter("page");
					}
	            }
	        } else {
	        	// 获取网页授权code失败，跳转错误提示页面
	        	logger.info("==============[OAuthServlet]获取网页授权code失败！");
	        	mav.setViewName("/error.jsp");
	        	return mav;
	        }
			
			HttpSession session = request.getSession();
			session.setAttribute("wx_id", wx_id);
			session.setAttribute("nickname", nickname);
			session.setAttribute("headimgurl", headimgurl);
			// mav.addObject("nickname", nickname);
			// mav.addObject("headimgurl", headimgurl);
			mav.setViewName(page);
		}
		return mav;
	}
	
	@RequestMapping(moduleName + "/signture")
	public @ResponseBody Map<String, String> getSignture(HttpServletRequest request) {
		String accessToken = WeixinUtil.getAccessToken(AppInfo.appId, AppInfo.appSecret).getToken();
		String jsapi_ticket = WeixinUtil.getJsApiTicket(accessToken).getTicket();
		String urls = request.getParameter("urls");
		return Sign.sign(jsapi_ticket, urls);
	}
}